package com.stock_t.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stock_t.entity.StockTTransaction;
import com.stock_t.entity.StockTrading;
import com.stock_t.mapper.StockTradingMapper;
import com.stock_t.service.StockTradingService;
import com.stock_t.service.StockTTransactionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class StockTradingServiceImpl extends ServiceImpl<StockTradingMapper, StockTrading> implements StockTradingService {
    
    @Autowired
    private StockTradingMapper stockTradingMapper;
    
    @Autowired
    private StockTTransactionService stockTTransactionService;
    
    @Override
    public boolean existsByTradeDateAndStockCode(Date tradeDate, String stockCode) {
        return !stockTradingMapper.selectByPrams(tradeDate, stockCode).isEmpty();
    }
    
    @Override
    public boolean saveOrUpdateWithCheck(StockTrading stockTrading) {
        // 检查是否已经存在同一天内相同股票的记录
        if (existsByTradeDateAndStockCode(stockTrading.getTradeDate(), stockTrading.getStockCode())) {
            // 如果存在，更新现有记录
            // 首先获取现有记录的ID
            StockTrading existingRecord = stockTradingMapper.selectByPrams(
                stockTrading.getTradeDate(), stockTrading.getStockCode()).get(0);
            
            // 将ID设置到新记录中，以便更新
            stockTrading.setId(existingRecord.getId());
            stockTrading.setUpdatedTime(new Date());
            // 更新记录
            return updateById(stockTrading);
        } else {
            stockTrading.setCreatedTime(new Date());
            // 如果不存在，直接保存新记录
            return save(stockTrading);
        }
    }
    
    // 获取股票列表
    @Override
    public List<Map<String, String>> getStockList() {
        return stockTradingMapper.selectStockList();
    }
    
    @Override
    @Transactional
    public boolean syncTProfit(Date tradeDate, String stockCode) {
        try {
            // 1. 查询当日该股票的做T总收益
            BigDecimal totalTProfit = stockTTransactionService.getTotalTProfitByDateAndStock(tradeDate, stockCode);
            
            // 2. 检查是否存在对应的股票交易记录
            List<StockTrading> tradingRecords = stockTradingMapper.selectByPrams(tradeDate, stockCode);
            
            if (!tradingRecords.isEmpty()) {
                // 3. 更新现有的股票交易记录的做T收益
                StockTrading tradingRecord = tradingRecords.get(0);
                tradingRecord.setTprofit(totalTProfit);
                return updateById(tradingRecord);
            } else {
                // 如果没有对应的股票交易记录，可以创建一条新记录或记录日志
                log.warn("未找到股票交易记录，股票编码：{}，交易日期：{}", stockCode, tradeDate);
                return false;
            }
        } catch (Exception e) {
            log.error("同步做T收益失败，股票编码：{}，交易日期：{}", stockCode, tradeDate, e);
            return false;
        }
    }
    
    @Override
    @Transactional
    public int syncAllTProfitByDate(Date tradeDate) {
        try {
            // 1. 获取该日期所有有做T交易的股票
            List<String> stockCodes = stockTTransactionService.list(
                new QueryWrapper<StockTTransaction>()
                    .select("DISTINCT stock_code")
                    .eq("transaction_date", tradeDate)
            ).stream()
            .map(StockTTransaction::getStockCode)
            .collect(Collectors.toList());
            
            int successCount = 0;
            
            // 2. 逐个同步每只股票的做T收益
            for (String stockCode : stockCodes) {
                if (syncTProfit(tradeDate, stockCode)) {
                    successCount++;
                }
            }
            
            log.info("同步完成，成功同步 {} 只股票的做T收益", successCount);
            return successCount;
        } catch (Exception e) {
            log.error("批量同步做T收益失败", e);
            return 0;
        }
    }
}